import * as config from '../config';
import store from '../store';

export const baseUrl = config.def().baseUrl;
export const staticUrl = config.def().staticUrl;

export const msg = (title, duration = 2000, mask = false, icon = 'none') => {
	if (Boolean(title) == false) {
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}

let setTimer = null;
export const logout = () => {
	store.commit('logout');
	if (['pages/index/index'].indexOf(currentRoute()) != -1) {
		if (!setTimer) {
			setTimer = true;
			let pre = currentPage();
			if (pre && pre.loadData) {
				pre.loadData('refresh');
			}
		}
	}

	if (['pages/login/index', 'pages/login/login', 'pages/login/sms', 'pages/index/index'].indexOf(
			currentRoute()) == -1) {
		if (!setTimer) {
			setTimer = true;
			uni.showModal({
				title: '提示',
				content: '请先登录？',
				success: res => {
					if (res.confirm) {
						uni.navigateTo({
							url: '/pages/login/index'
						});
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				},
				complete: res => {
					setTimer = null;
				}
			});
		}
	}
}
// export const logout = () => {
// 	if (['pages/login/index', 'pages/login/login', 'pages/login/sms', 'pages/index/index'].indexOf(currentRoute()) == -1) {
// 		store.commit('logout');
// 		uni.showToast({
// 			title: '请先登录',
// 			icon: 'none'
// 		});
// 		if (setTimer) {
// 			clearTimeout(setTimer);
// 		}
// 		setTimer = setTimeout(() => {
// 			uni.navigateTo({
// 				url: '/pages/login/index'
// 			});
// 		}, 500);
// 	}
// }

export const request = (api, data = {}, header = {}) => {
	return new Promise(resolve => {
		let userInfo = store.getters.getUserInfo;
		let Authorization = userInfo.Authorization || '';
		let userId = userInfo.sysUser ? userInfo.sysUser.id : '';
		let load = header.load;
		let method = header.method || 'POST';
		let content = header.content || 'application/json';
		load && uni.showLoading({
			title: '加载中...',
			mask: true
		});
		uni.request({
			url: baseUrl + api,
			data: {
				...data,
				rest: userId
			},
			method: method,
			header: {
				'Content-Type': content,
				'Authorization': Authorization
			},
			success: (res) => {
				load && uni.hideLoading();
				if (res.statusCode == 200) {
					if (res.data.code == 200) {
						resolve(res.data);
					} else {
						console.log(api);
						console.log(res.data);
						let errorMsg = res.data.msg ? res.data.msg : res.data.data.msg;
						uni.showToast({
							title: errorMsg,
							icon: 'none'
						});
						if (errorMsg.indexOf('手机号未注册') > -1) {
							resolve(res.data);
						}
					}
				} else if (res.statusCode == 401) {
					logout();
				} else {
					console.log(res.data);
					uni.showToast({
						title: '请求失败！',
						icon: 'none'
					});
				}
			},
			fail: (res) => {
				load && uni.hideLoading();
				uni.showToast({
					title: '服务器连接失败！',
					icon: 'none'
				});
			}
		})
	})
}

export const checkRules = (params, rules) => { //表单校验
	for (let key in rules) {
		let arr = rules[key]
		for (let i = 0; i < arr.length; i++) {
			let rule = arr[i],
				val = params[key] === 0 ? '0' : params[key] || ''
			if (rule.required && val === '') { //非空
				uni.showToast({
					title: rule.message,
					icon: "none"
				});
				return false
			}
			if (rule.pattern && !rule.pattern.test(val)) { //正则
				uni.showToast({
					title: rule.message,
					icon: "none"
				});
				return false
			}
		}
	}
	return true
}

export const prePage = () => {
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 2];
	return prePage ? prePage.$vm : null;
}

export const currentPage = () => {
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 1];
	return prePage ? prePage.$vm : null;
}

export const currentRoute = () => {
	let pages = getCurrentPages();
	let prePage = pages[pages.length - 1];
	// #ifdef H5
	return prePage ? prePage.$vm.route : null;
	// #endif
	return prePage ? prePage.$vm.__route__ : null;
}

export const getStatusBarHeight = () => {
	uni.getSystemInfoSync({
		success: res => {
			return res.statusBarHeight;
		},
		fail: res => {
			return '0'
		}
	});
}

export const randomColor = (len) => {
	len = len || 32;
	let chars = 'abcdef1234567890';
	let maxPos = chars.length;
	let color = '';
	for (let i = 0; i < len; i++) {
		color += chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return color;
}

export const randomNum = () => {
	// return Math.round(Math.random()*9998);
	let deta = new Date();
	let time = deta.getTime().toString();
	return time.substring(0, 8);
}

export const random = (min, max) => {
	return Math.floor(Math.random() * (max - min)) + min;
}

export const htmlRegx = (html) => {
	//去掉html标签
	let regx = /<[^>]*>|<\/[^>]*>/gm;
	let text = '';
	if (html) {
		text = html.replace(regx, '');
	}
	return text;
}

export const imgRegx = (html) => {
	let regex = new RegExp(/src=/g);
	let imgHtml = '';
	if (html) {
		imgHtml = html.replace(regex, 'style="display: block;margin: 0 auto;max-width: 100%;" src=');
	}
	return imgHtml;
}

export const imgRegxF = (html) => {
	let regex = new RegExp(/src=['"]([^'"]+)[^>]*/i);
	let imgHtml = '';
	if (html) {
		imgHtml = html.match(regex);
	}
	if (imgHtml) {
		return imgHtml[1].replace(/&amp;/g, '&');
	} else {
		return staticUrl + '/static/img/sheqingminyi1.png';
		// http://58.57.77.174:8877/file/download/wangEditor/2023072108221529971132.png/f6ce642094cf2ee83c2f193b4531732a_640_wx_fmt=png&amp;wxfrom=5&amp;wx_lazy=1&amp;wx_co=1.png
		// return random(1, 3) == 1 ? staticUrl + '/static/img/sheqingminyi1.png' : staticUrl + '/static/img/sheqingminyi2.png';
	}
}

export const parseTime = (time, cFormat) => {
	if (!arguments[0] || arguments.length == 0) {
		return null;
	}
	if (arguments[0] && arguments[0].length <= 10) {
		return arguments[0] + ' ';
	}
	const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}';
	let date;
	if (typeof time == 'object') {
		date = time;
	} else {
		if (('' + time).length == 10) time = parseInt(time) * 1000;
		if (typeof time == 'string') time = time.replace(/\-/g, '/').replace('T', ' ').substring(0, 18);
		date = new Date(time);
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key];
		if (key == 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value];
		}
		if (result.length > 0 && value < 10) {
			value = '0' + value;
		}
		return value || 0;
	})
	if (time_str == '0-0-0') return ' ';
	return time_str + ' ';
}

export const imagePreview = (imagePath) => {
	if (imagePath && imagePath.indexOf('http') != -1) {
		return imagePath;
	}
	if (imagePath) {
		imagePath = imagePath.replace(/\\/g, '/');
		return baseUrl + '/file/download/preview/0/?path=' + imagePath;
	} else {
		return '/static/img/theme@2x.png';
	}
}

export const imagePathGroup = (imagePath, imageName) => {
	if (imagePath) {
		imagePath = imagePath.replace(/\\/g, '/');
		return baseUrl + '/file/download/preview/0/?path=' + imagePath;
	} else {
		return '/static/img/theme@2x.png';
	}
}

export const staticImg = (imagePath) => {
	if (!imagePath) {
		return false;
	}
	return staticUrl + imagePath;
}

export const staticImgRandom = (imagePath) => {
	if (!imagePath) {
		return false;
	}
	return staticUrl + imagePath + '?' + randomNum();
}

export const showLine = (item) => {
	let imgType = 'bmp,jpg,jpeg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,webp';
	let fileType = 'doc,docx,xls,xlsx,ppt,pptx,pdf,txt';
	let audioType = 'm4a,wav,mp3,aac';
	if (!item.name) {
		return false;
	}
	let name = item.name.split('.');
	let url = baseUrl + '/file/download/' + item.id;
	if (imgType.indexOf(name[name.length - 1].toLowerCase()) != -1) {
		uni.previewImage({
			urls: [url]
		});
	} else if (audioType.indexOf(name[name.length - 1].toLowerCase()) != -1) {
		downLine(item);
	} else if (fileType.indexOf(name[name.length - 1].toLowerCase()) != -1) {
		downLine(item);
	} else {
		uni.showToast({
			title: '暂不支持此格式预览',
			icon: 'none'
		});
	}
}

export const downLine = (item) => {
	if (!item.name) {
		return false;
	}
	let name = item.name.split('.');
	let url = baseUrl + '/file/download/' + item.id;
	let path = item.path;
	uni.showLoading({
		title: '下载中'
	});
	const downloadTask = uni.downloadFile({
		url: url,
		success: (res) => {
			uni.hideLoading();
			const filePath = res.tempFilePath;
			uni.openDocument({
				filePath: filePath,
				showMenu: true
			});
		},
		fail: (res) => {
			uni.hideLoading();
			uni.showToast({
				title: '下载失败',
				icon: 'none'
			});
		}
	})

	downloadTask.onProgressUpdate(res => {});
}

export const qrcodeResult = (res) => {
	try {
		let resulet = JSON.parse(res.result);
		let userInfo = store.getters.getUserInfo;
		if (resulet.type == 'huiyi') {
			let typeMap = {
				'1': '扫码签到',
				'2': '刷脸签到',
				'3': '手动签到',
				'4': '代为签到'
			};
			let data = {
				signType: '1',
				meetingId: resulet.data.id,
				userId: userInfo.sysUser.id
			};
			request('/huiyihuodong/hyhd-meeting-user/signTime', data, {
				load: true
			}).then(res => {
				if (!res.data.firstSign && res.data.signType && res.data.signTime) {
					uni.showModal({
						title: '已通过' + typeMap[res.data.signType],
						content: '签到时间：' + res.data.signTime,
						complete: () => {
							uni.switchTab({
								url: '/pages/index/index'
							});
						}
					});
				} else {
					uni.showToast({
						title: '签到成功！',
						icon: 'none'
					});
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/index/index'
						});
					}, 500);
				}
			});
		} else if (resulet.type == 'xsys') {
			let data = {
				consultSign: {
					infoid: resulet.data.id,
					userId: userInfo.sysUser.id,
					userName: userInfo.sysUser.userName
				}
			};
			this.$request('/xieshangyishi/consultSign/sign/add', data, {
				load: true
			}).then(res => {
				uni.showToast({
					title: '签到成功！',
					icon: 'none'
				});
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/index/index'
					});
				}, 500);
			});
		} else if (resulet.type == 'loginQr') {
			let data = {
				step: '3',
				qrId: resulet.data.id,
				userId: userInfo.sysUser.id
			};
			request('/loginQr', data, {
				load: true
			}).then(res => {
				uni.navigateTo({
					url: '/pages/login/qrcode?qrId=' + resulet.data.id
				});
			});
		} else {
			uni.showToast({
				title: resulet,
				icon: 'none'
			});
		}
	} catch (e) {
		uni.showToast({
			title: '扫描失败',
			icon: 'none'
		});
	}
}

export const roleCodes = (e) => {
	let roleCodes = store.getters.getUserInfo.roleCodes;
	if (!roleCodes) return;
	return roleCodes.some((item) => {
		return item == e;
	});
}

export const sysBtns = (e) => {
	let sysBtns = store.getters.getUserInfo.sysBtns;
	if (!sysBtns) return;
	return sysBtns.some((item) => {
		return item.menuCode == e;
	});
}

export const sysMenus = (e) => {
	let sysMenus = store.getters.getUserInfo.sysMenus;
	if (!sysMenus) return;
	return sysMenus.some((item) => {
		return item.menuCode == e;
	});
}

export const sysMenusName = (e) => {
	let sysMenus = store.getters.getUserInfo.sysMenus;
	if (!sysMenus) return;
	return sysMenus.some((item) => {
		return item.menuName == e;
	});
}

export function nullHelp(e) {
	if (e === null || e == 'null') {
		return '';
	} else {
		return e;
	}
}

export const filterSize = (limit) => {
	let size = "";
	if (limit < 0.1 * 1024) {
		size = limit.toFixed(2) + "B";
	} else if (limit < 0.1 * 1024 * 1024) {
		size = (limit / 1024).toFixed(2) + "KB";
	} else if (limit < 0.1 * 1024 * 1024 * 1024) {
		size = (limit / (1024 * 1024)).toFixed(2) + "MB";
	} else {
		size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
	}

	let sizeStr = size + "";
	let index = sizeStr.indexOf(".");
	let dou = sizeStr.substr(index + 1, 2);
	if (dou == "00") {
		return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2);
	}
	return size;
}

export const writeCurrentDate = () => {
	let now = new Date();
	let year = now.getFullYear();
	let month = now.getMonth();
	let date = now.getDate();
	let day = now.getDay();
	let hour = now.getHours();
	let minu = now.getMinutes();
	let sec = now.getSeconds();
	let MS = now.getMilliseconds();
	let week;
	month = month + 1;
	if (month < 10) month = "0" + month;
	if (date < 10) date = "0" + date;
	if (hour < 10) hour = "0" + hour;
	if (minu < 10) minu = "0" + minu;
	if (sec < 10) sec = "0" + sec;
	if (MS < 100) MS = "0" + MS;
	let arr_week = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
	week = arr_week[day];
	let time = "";
	time = year + "年" + month + "月" + date + "日" + " " + hour + ":" + minu + ":" + sec + " " + week;
	let apm = '';
	if (hour >= 7 && hour < 11) {
		apm = "上午好";
	} else if (hour >= 11 && hour < 14) {
		apm = "中午好";
	} else if (hour >= 14 && hour < 18) {
		apm = "下午好";
	} else if (hour >= 18 && hour < 23) {
		apm = "晚上好";
	} else {
		apm = "请注意休息";
	}
	let obj = {
		year: year,
		month: month,
		date: date,
		hour: hour,
		minu: minu,
		sec: sec,
		week: week,
		time: time,
		data: month + '' + date,
		apm: apm
	}
	return obj;
}

export const bd09_to_gcj02 = (lng, lat) => {
	let x = lng - 0.0065,
		y = lat - 0.006;
	let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * Math.PI);
	let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * Math.PI);
	return {
		lng: z * Math.cos(theta),
		lat: z * Math.sin(theta)
	};
}

export const gcj02_to_bd09 = (lng, lat) => {
	let z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * Math.PI);
	let theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * Math.PI);
	return {
		lng: z * Math.cos(theta) + 0.0065,
		lat: z * Math.sin(theta) + 0.006
	};
}

export const pointInsideCircle = (lng_a, lat_a, lng_b, lat_b, r) => {
	let pk = 180 / 3.1415926;
	let a1 = lat_a / pk;
	let a2 = lng_a / pk;
	let b1 = lat_b / pk;
	let b2 = lng_b / pk;
	let t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
	let t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
	let t3 = Math.sin(a1) * Math.sin(b1);
	let tt = Math.acos(t1 + t2 + t3);
	return Math.floor(6366000 * tt) <= r;
}

export const isSameDay = (timeStampA) => {
	if (typeof timeStampA == 'string') timeStampA = timeStampA.replace(/\-/g, '/').replace('T', ' ');

	let dateA = new Date(timeStampA);
	let dateB = new Date();
	return (dateA.setHours(0, 0, 0, 0) == dateB.setHours(0, 0, 0, 0));
}

export function daysBetweenNum(bdate, edate) {
	if (typeof bdate == 'string') bdate = bdate.replace(/\-/g, '/').replace('T', ' ');
	if (typeof edate == 'string') edate = edate.replace(/\-/g, '/').replace('T', ' ');

	let oneDayMillisecond = 86400000;
	let bdateMillisecond = new Date(bdate).getTime();
	let edateMillisecond = new Date(edate).getTime();
	let diffMillisecond = edateMillisecond - bdateMillisecond;
	let diffDays = Math.floor(Math.abs(diffMillisecond / oneDayMillisecond));
	let date_arr = [];

	for (let index = 0; index <= diffDays; index++) {
		let new_date = parseTime(bdateMillisecond + oneDayMillisecond * index, '{y}-{m}-{d}').trim();
		date_arr.push(new_date);
	}
	return date_arr.length - 1;
}

let token = uni.getStorageSync('baiduToken');
let index = 0;
let length = 0;
let arr = [];
let list = [];
let click = false;
let ended = false;
let loading = false;
let innerAudioContext = '';

function getMp3(text) {
	let param = {
		tex: text,
		tok: token,
		spd: 5,
		pit: 5,
		vol: 5,
		per: 1,
		cuid: token,
		lan: 'zh',
		aue: 'zh',
		ctp: 1
	}
	innerAudioContext.src =
		'https://tsn.baidu.com/text2audio?lan=zh&ctp=1&cuid=' + token + '&tok=' + token +
		'&vol=5&per=1&spd=5&pit=5&aue=3&tex=' + encodeURIComponent(encodeURIComponent(text));
	setTimeout(() => {
		innerAudioContext.play();
		ended = true;
	}, 100);
}

export const ttsOff = () => {
	if (innerAudioContext) {
		innerAudioContext.destroy();
	}
	innerAudioContext = '';
}

export const tts = (text, _this, section = 500) => {
	if (innerAudioContext) {
		if (_this.play == false) {
			innerAudioContext.play();
		} else {
			innerAudioContext.pause();
		}
	} else {
		let str = text;
		index = 0;
		arr = [];
		list = [];
		length = Math.ceil(str.length / section);
		innerAudioContext = uni.createInnerAudioContext();
		if (uni.setInnerAudioOption) {
			uni.setInnerAudioOption({
				autoplay: true,
				obeyMuteSwitch: false
			});
		} else {
			innerAudioContext.autoplay = true;
			innerAudioContext.obeyMuteSwitch = false;
		}

		for (let i = 0; i < length; i++) {
			arr.push(str.substring(i * section, section * (i + 1)));
		}

		getMp3(arr[index]);
		index++;

		innerAudioContext.onPlay(() => {
			console.log('onPlay');
			_this.play = true;
		});
		innerAudioContext.onStop(() => {
			console.log('onStop');
			_this.play = false;
		});
		innerAudioContext.onPause(() => {
			console.log('onPause');
			_this.play = false;
		});
		innerAudioContext.onError((res) => {
			console.log('onError');
			_this.play = false;
		});
		innerAudioContext.onEnded(() => {
			console.log('onEnded');
			if (index < length) {
				console.log(index + '播放结束');
				getMp3(arr[index]);
				index++;
			} else {
				console.log('全部播放结束!');
				uni.showToast({
					title: '全部播放结束',
					icon: 'none'
				});
				ended = false;
				_this.play = false;
				innerAudioContext.destroy();
				innerAudioContext = '';
			}
		});
	}
}
